<?php
$table = 'table_name';
$outstr = NULL;

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");
mysql_select_db("stms");

// Query database to get column names  
$result = mysql_query("show columns from new",$connect);
// Write column names
while($row = mysql_fetch_array($result)){
    $outstr.= $row['id'].',';
}  
$outstr = substr($outstr, 0, -1)."\n";

// Query database to get data
$result = mysql_query("select * from new",$connect);
// Write data rows
while ($row = mysql_fetch_assoc($result)) {
    $outstr.= join(',', $row)."\n";
}

echo $outstr;
mysql_close($connect);
?>